import React, { Component } from 'react';
import { StyleSheet, TouchableOpacity, TextInput, Image } from 'react-native';
import { Container, Content, View, Toast, Text, Icon } from 'native-base';
import { ListItem } from 'react-native-elements';
import LinearGradient from 'react-native-linear-gradient';
import { connect } from 'react-redux';
import Moment from 'moment';
import ImagePicker from 'react-native-image-crop-picker';
import { CODE, ZONE, upload } from '@react-native-hero/qiniu';

import { Header, Loading } from '../../component';
import { Colors, Metrics } from '../../theme';


class ZhuanfaFx extends Component {
	constructor(props) {
		super(props);
		this.state = {
			appName: '', // 主体APP名称
			title: '', // 标题
			describe: '', // 描述
			addressLink: '', // 链接
			buzouArr: [{
				tit: '图文说明',
				placeholder: '请填写任务步骤图文说明',
				text: '',
				imgs: '',
			}], // 步骤
			submitText: '', // 提交收集
			isLoading: false,
		}
	}

	deleteBlockFunc(index){
		let arr = this.state.buzouArr || [];
		arr.splice(index, 1);
		this.setState({ buzouArr: arr });
	}

	deleteImgFunc(index) {
		let arr = this.state.buzouArr || [];
		arr[index].imgs = '';
		this.setState({ buzouArr: arr });
	}

	changeTextFunc(index, text) {
		let arr = this.state.buzouArr || [];
		arr[index].text = text;
		this.setState({ buzouArr: arr });
	}

	addBuzouFunc(type) {
		let arr = this.state.buzouArr || [];
		if (arr.length>5) {
			Toast.show({ text: "添加步骤过多！", textStyle: { textAlign: "center" }, type: "warning" });
		}
		if (type == '1') {
			arr.push({
				tit: '图文说明',
				placeholder: '请填写任务步骤图文说明',
				text: '',
				imgs: '',
			})
		} else {
			arr.push({
				tit: '收集截图',
				placeholder: '请填写说明要截取哪个界面，重点位置',
				text: '',
				imgs: '',
			})
		}

		this.setState({ buzouArr: arr })

	}

	//  上传
	uploadImgFunc(index) {
		ImagePicker.openPicker({
			cropperToolbarTitle: '选取图片',
			mediaType: 'photo'
		}).then((res) => {
			let path = res.path.replace('file://', '');
			upload(
				{
					key: 'shichai/' + this.props.token + '/' + res.modificationDate,
					// 上传文件的本地路径
					path: path,
					// 上传文件的 mime type
					mimeType: res.mime,
					// 上传凭证，通常由服务器生成传给客户端
					token: this.props.global.qiniuToken,
					// 机房，传入 ZONE 的枚举值
					zone: ZONE.HUADONG,
				}
			)
				.then(data => {
					// 上传成功，data 是七牛服务器返回的数据
					console.log('data1', data)
					let arr = this.state.buzouArr || [];
					arr[index].imgs = this.props.global.qiniuBaseUri + data.key;
					this.setState({ buzouArr: arr });
				})
				.catch(err => {
					if (err.code === CODE.UPLOAD_FAILURE) {
						console.log('upload error', err)
					}
				})
		}).catch(err => {
			console.log('用户取消');
		})
	}


	UNSAFE_componentWillMount() {

	}

	componentDidMount() {

	}

	junpBuzouFunc() {
		// if (this.state.appName.length<2 || this.state.appName.length>10) {
		// 	Toast.show({ text: "请填写正确的项目名称！", textStyle: { textAlign: "center" }, type: "warning" });
		// 	return false;
		// }
		// if (this.state.title.length<2 || this.state.title.length>10) {
		// 	Toast.show({ text: "请填写正确的任务标题！", textStyle: { textAlign: "center" }, type: "warning" });
		// 	return false;
		// }

		// if (this.state.buzouArr.length<2) {
		// 	Toast.show({ text: "操作步骤过少", textStyle: { textAlign: "center" }, type: "warning" });
		// 	return false;
		// }

		// if (!this.state.addressLink) {
		// 	Toast.show({ text: "请填写正确的任务链接", textStyle: { textAlign: "center" }, type: "warning" });
		// 	return false;
		// }

		// if (!this.state.submitText) {
		// 	Toast.show({ text: "请填写提交数据", textStyle: { textAlign: "center" }, type: "warning" });
		// 	return false;
		// }

		this.props.setPublishInfo({
			publishType: '3',
			appName: this.state.appName,
			title: this.state.title,
			describe: this.state.describe,
			addressLink: this.state.addressLink,
			buzouArr: this.state.buzouArr,
			submitText: this.state.submitText,
		});
		this.props.navigation.navigate('OrderPlace');
	}

	render() {
		return (
			<Container>
				<Header title="分享转发1/2" onLeftPress={() => this.props.navigation.goBack()} />
				<Loading showLoading={this.state.isLoading} />
				<Content>
					<View style={Styles.container}>
						<View style={Styles.buzou1}>
							<Text style={Styles.inputTit}>任务标题 <Text style={{ color: Colors.hong }}>*</Text> </Text>
							<TextInput
								inputStyle={Styles.inputText}
								placeholder='请输入任务标题(2-10字)'
								value={this.state.title}
								onChangeText={(value) => this.setState({ title: value })}
							/>

							<Text style={Styles.inputTit}>任务描述 </Text>
							<TextInput
								inputStyle={Styles.inputText}
								placeholder='请输入任务描述，具体要求，限制条件等'
								value={this.state.describe}
								onChangeText={(value) => this.setState({ describe: value })}
							/>

							<Text style={Styles.inputTit}>任务链接 <Text style={{ color: Colors.hong }}>*</Text> </Text>
							<TextInput
								inputStyle={Styles.inputText}
								placeholder='任务链接'
								value={this.state.addressLink}
								onChangeText={(value) => this.setState({ addressLink: value })}
							/>
						</View>

						<View style={{ height: 10, backgroundColor: Colors.huiED }}></View>

						<View style={Styles.buzou1}>
							<View style={Styles.flexZy}>
								<Text style={Styles.inputTit}>任务步骤<Text style={{ color: Colors.hong }}>*</Text> </Text>
								<Text style={{ color: Colors.subjectJbZuo, fontSize: 15 }} onPress={() => this.addBuzouFunc(1)}> + 图文说明 </Text>
								<Text style={{ color: Colors.subjectJbZuo, fontSize: 15 }} onPress={() => this.addBuzouFunc(2)}> + 收集信息 </Text>
							</View>


							<View style={Styles.xunhuanBzCont}>
								{
									this.state.buzouArr.map((l, i) => (
										<View key={i} style={Styles.xunhuanCont}>
											<View style={Styles.flexZy}>
												<Text style={Styles.inputTit}> 第{i + 1}步（{l.tit}） </Text>
												<Icon type="AntDesign" name='close' style={Styles.closeIcons} onPress={() => this.deleteBlockFunc(i)}/>
											</View>
											<TextInput
												inputStyle={Styles.inputText}
												placeholder={l.placeholder}
												value={l.text}
												onChangeText={(text) => this.changeTextFunc(i, text)}
											/>

											{
												l.imgs ?
													<View style={Styles.jietuImgTrueCont}>
														<TouchableOpacity  onPress={() => this.deleteImgFunc(i)} style={Styles.closeIconPosiCont}>
															<Icon type="AntDesign" name='close' style={Styles.closeIconPosi} />
														</TouchableOpacity>
														<Image style={Styles.jietuImgTrue} source={{ uri: l.imgs }} />
													</View>
													:
													<TouchableOpacity onPress={() => this.uploadImgFunc(i)} style={Styles.jietuImgCont}>
														<Icon type="AntDesign" name='plus' style={Styles.jietuImg} />
													</TouchableOpacity>
											}

										</View>
									))
								}


							</View>
						</View>

					</View>

					<View style={Styles.btnContentView}>
						<TouchableOpacity onPress={() => this.junpBuzouFunc()} disabled={this.state.isLoading}>
							<LinearGradient style={{ width: Metrics.screenWidth * 0.6, alignItems: "center", borderRadius: 8 }} colors={[Colors.subjectJbZuo, Colors.subject]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}>
								<Text style={{ fontSize: 14, padding: 12, color: Colors.bai }}>{`${this.state.isLoading ? "请求中..." : "下一步"}`}</Text>
							</LinearGradient>
						</TouchableOpacity>
					</View>

				</Content>
			</Container>
		);
	}

}

const mapStateToProps = state => ({
	logged: state.user.logged,
	publish: state.publish,
	token: state.user.token,
	global: state.global,
});

const mapDispatchToProps = dispatch => ({
	setPublishInfo: publishInfo => dispatch({ type: 'SET_PUBLISHINFO', payload: { publishInfo } }),
});

export default connect(mapStateToProps, mapDispatchToProps)(ZhuanfaFx);

const Styles = StyleSheet.create({
	container: { flex: 1, backgroundColor: '#FFFFFF' },
	btnContentView: { marginTop: 20, marginBottom: 20, alignItems: "center" },
	buzou1: { padding: 10 },
	inputTit: {
		fontSize: Metrics.fontSize14,
		color: Colors.hui33,
		marginTop: 6,
		marginLeft: 6
	},
	flexZy: {
		flexDirection: 'row',
		flexWrap: 'wrap',
		justifyContent: 'space-between',
		alignItems: 'center',
		marginTop: 6
	},
	xunhuanCont: {
		marginTop: 20,
		borderTopWidth: StyleSheet.hairlineWidth,
		borderTopColor: Colors.hui99,
	},
	closeIcons: {
		fontSize: Metrics.fontSize16,
		color: Colors.hui99,
		marginRight: 10
	},
	jietuImgTrueCont: {
		position: 'relative',
		width: Metrics.screenWidth / 4, height: Metrics.screenWidth / 4
	},
	closeIconPosiCont: {
		position: 'absolute',
		top: -8,
		right: -8,
		zIndex: 9,
	},
	closeIconPosi: {
		fontSize: Metrics.fontSize16,
		backgroundColor: Colors.hui99,
		borderRadius: 10,
		color: Colors.bai,
		padding: 2
	},
	jietuImgTrue: {
		width: Metrics.screenWidth / 4, height: Metrics.screenWidth / 4
	},
	jietuImgCont: {
		width: Metrics.screenWidth / 4, height: Metrics.screenWidth / 4,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		borderWidth: StyleSheet.hairlineWidth,
		borderColor: Colors.hui99
	},
	jietuImg: { fontSize: 40, color: Colors.hui99 },
	inputText: {

	}
});